<template>
  <div class="category-list">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加分类
      </el-button>
    </div>

    <!-- 分类列表 -->
    <el-card class="list-card">
      <el-table
        :data="categoryList"
        style="width: 100%"
        v-loading="loading"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="分类名称" min-width="200">
          <template #default="{ row }">
            <span>{{ row.name }}</span>
            <el-tag
              v-if="row.isLeaf"
              type="info"
              size="small"
              class="leaf-tag"
            >
              叶子节点
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="层级" width="100" />
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.level < 2"
              type="primary"
              link
              @click="handleAdd(row)"
            >
              添加子分类
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分类表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加分类' : '编辑分类'"
      width="800px"
      destroy-on-close
      class="category-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="category-form"
      >
        <el-form-item label="上级分类">
          <el-cascader
            v-model="form.parentId"
            :options="categoryOptions"
            :props="{
              checkStrictly: true,
              value: 'id',
              label: 'name',
              children: 'children'
            }"
            clearable
            placeholder="请选择上级分类"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="属性模板" class="attribute-template-item">
          <el-tabs type="border-card" class="attribute-tabs">
            <el-tab-pane label="必选属性">
              <div class="attributes-container">
                <template v-if="requiredAttributes.length > 0">
                  <el-table :data="requiredAttributes" border style="width: 100%">
                    <el-table-column label="属性名称" min-width="300">
                      <template #default="{ row }">
                        <el-input v-model="row.name" placeholder="请输入属性名称" clearable />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100" align="center">
                      <template #default="{ $index }">
                        <el-button type="danger" circle @click="removeRequiredAttribute($index)">
                          <el-icon><Delete /></el-icon>
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
                <el-empty v-else description="暂无必选属性" :image-size="80" />
              </div>
              <div class="add-button-row">
                <el-button type="primary" @click="addRequiredAttribute" plain>
                  <el-icon><Plus /></el-icon>
                  添加必选属性
                </el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="可选属性">
              <div class="attributes-container">
                <template v-if="optionalAttributes.length > 0">
                  <el-table :data="optionalAttributes" border style="width: 100%">
                    <el-table-column label="属性名称" min-width="300">
                      <template #default="{ row }">
                        <el-input v-model="row.name" placeholder="请输入属性名称" clearable />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100" align="center">
                      <template #default="{ $index }">
                        <el-button type="danger" circle @click="removeOptionalAttribute($index)">
                          <el-icon><Delete /></el-icon>
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
                <el-empty v-else description="暂无可选属性" :image-size="80" />
              </div>
              <div class="add-button-row">
                <el-button type="primary" @click="addOptionalAttribute" plain>
                  <el-icon><Plus /></el-icon>
                  添加可选属性
                </el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { getCategoryList, addCategory, updateCategory, deleteCategory } from '@/api/category'
import service from '@/utils/request'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

// 分类列表
const categoryList = ref([])
// 分类选项（用于级联选择器）
const categoryOptions = ref([])

// 表单数据
const form = ref({
  id: null,
  name: '',
  parentId: null,
  level: 1,
  isLeaf: false,
  attributeTemplate: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 属性模板列表
const requiredAttributes = ref([])
const optionalAttributes = ref([])

// 将表单中的JSON字符串转换为可编辑的属性列表
const parseAttributeTemplate = () => {
  try {
    if (form.value.attributeTemplate && form.value.attributeTemplate.trim()) {
      const template = JSON.parse(form.value.attributeTemplate)
      
      // 处理必选属性
      if (template.required) {
        requiredAttributes.value = Array.isArray(template.required) 
          ? template.required.map(name => ({ name }))
          : Object.keys(template.required).map(name => ({ name }))
      } else {
        requiredAttributes.value = []
      }
      
      // 处理可选属性
      if (template.optional) {
        optionalAttributes.value = Array.isArray(template.optional)
          ? template.optional.map(name => ({ name }))
          : Object.keys(template.optional).map(name => ({ name }))
      } else {
        optionalAttributes.value = []
      }
    } else {
      requiredAttributes.value = []
      optionalAttributes.value = []
    }
  } catch (error) {
    console.error('解析属性模板失败：', error)
    ElMessage.error('属性模板格式错误，已重置为空')
    requiredAttributes.value = []
    optionalAttributes.value = []
  }
}

// 将编辑后的属性列表转换回JSON字符串
const updateAttributeTemplate = () => {
  try {
    // 提取必选属性
    const required = requiredAttributes.value
      .filter(attr => attr.name.trim() !== '')
      .map(attr => attr.name.trim())
    
    // 提取可选属性
    const optional = optionalAttributes.value
      .filter(attr => attr.name.trim() !== '')
      .map(attr => attr.name.trim())
    
    // 构建对象并转换为JSON
    const template = {
      required,
      optional
    }
    
    form.value.attributeTemplate = JSON.stringify(template)
  } catch (error) {
    console.error('生成属性模板失败：', error)
  }
}

// 添加必选属性
const addRequiredAttribute = () => {
  const newAttr = { name: '' }
  requiredAttributes.value.push(newAttr)
  updateAttributeTemplate()
}

// 删除必选属性
const removeRequiredAttribute = (index) => {
  requiredAttributes.value.splice(index, 1)
  updateAttributeTemplate()
}

// 添加可选属性
const addOptionalAttribute = () => {
  const newAttr = { name: '' }
  optionalAttributes.value.push(newAttr)
  updateAttributeTemplate()
}

// 删除可选属性
const removeOptionalAttribute = (index) => {
  optionalAttributes.value.splice(index, 1)
  updateAttributeTemplate()
}

// 监听属性列表变化，更新JSON
watch([requiredAttributes, optionalAttributes], () => {
  updateAttributeTemplate()
}, { deep: true })

// 监听对话框显示状态，初始化属性列表
watch(dialogVisible, (val) => {
  if (val) {
    parseAttributeTemplate()
  }
})

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载分类列表
const loadCategoryList = async () => {
  loading.value = true
  try {
    const res = await getCategoryList()
    categoryList.value = res
    // 处理分类选项数据
    categoryOptions.value = [
      { id: 0, name: '顶级分类', children: res }
    ]
  } catch (error) {
    console.error('加载分类列表失败：', error)
    ElMessage.error('加载分类列表失败')
  } finally {
    loading.value = false
  }
}

// 计算分类层级
const getCategoryLevel = (category) => {
  // 如果没有parentId或parentId为0或null，则为一级分类
  if (!category.parentId) return 1
  
  // 找到对应的父分类
  const findParentCategory = (id, categories) => {
    for (const cat of categories) {
      if (cat.id === id) {
        return cat
      }
      if (cat.children && cat.children.length > 0) {
        const found = findParentCategory(id, cat.children)
        if (found) return found
      }
    }
    return null
  }
  
  // 查找父分类
  const parent = findParentCategory(category.parentId, categoryList.value)
  
  // 如果父分类不存在或者没有parentId，说明是二级分类
  if (!parent || !parent.parentId) {
    return 2 // 二级分类
  } else {
    return 3 // 三级分类
  }
}

// 在表格中添加辅助列，用于调试分类层级
const getDebugCategoryLevel = (row) => {
  const level = getCategoryLevel(row)
  console.log(`分类: ${row.name}, ID: ${row.id}, 父ID: ${row.parentId}, 层级: ${level}`)
  return level
}

// 添加分类
const handleAdd = (row) => {
  // 检查是否可以添加子分类
  if (row && row.level >= 2) {
    ElMessage.warning('最多支持二级分类')
    return
  }
  
  dialogType.value = 'add'
  form.value = {
    id: null,
    parentId: row ? row.id : null,
    name: '',
    level: row ? row.level + 1 : 1,
    isLeaf: row ? (row.level + 1 >= 2) : false,
    attributeTemplate: ''
  }
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = {
    id: row.id,
    parentId: row.parentId,
    name: row.name,
    level: row.level,
    isLeaf: row.isLeaf,
    attributeTemplate: row.attributeTemplate || ''
  }
  dialogVisible.value = true
}

// 删除分类
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该分类吗？删除后不可恢复！',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteCategory(row.id)
    ElMessage.success('删除成功')
    loadCategoryList()
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除失败：', error)
    ElMessage.error('删除失败，请重试')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    // 确保parentId是单个值而不是数组
    if (Array.isArray(form.value.parentId) && form.value.parentId.length > 0) {
      // 取数组最后一个元素作为parentId
      form.value.parentId = form.value.parentId[form.value.parentId.length - 1]
    } else if (Array.isArray(form.value.parentId) && form.value.parentId.length === 0) {
      // 空数组设为null
      form.value.parentId = null
    }
    
    // 设置分类层级和叶子节点属性
    if (form.value.parentId) {
      // 如果有父级，则层级为父级层级+1
      const parent = categoryList.value.find(c => c.id === form.value.parentId) || 
                    categoryList.value.flatMap(c => c.children || []).find(c => c.id === form.value.parentId)
      
      if (parent) {
        form.value.level = parent.level + 1
        // 如果当前层级已经是2，则为叶子节点
        form.value.isLeaf = form.value.level >= 2
      }
    } else {
      // 顶级分类
      form.value.level = 1
      form.value.isLeaf = false
    }
    
    if (dialogType.value === 'add') {
      await addCategory(form.value)
      ElMessage.success('添加成功')
    } else {
      await updateCategory(form.value)
      ElMessage.success('修改成功')
    }
    
    dialogVisible.value = false
    loadCategoryList()
  } catch (error) {
    if (error === 'cancel') return
    console.error('操作失败：', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 获取属性类型描述
const getTypeDescription = (type) => {
  const typeMap = {
    'text': '文本输入框',
    'number': '数字输入框',
    'boolean': '是/否开关',
    'date': '日期选择器'
  }
  return typeMap[type] || '未知类型'
}

onMounted(() => {
  loadCategoryList()
})
</script>

<style lang="scss" scoped>
.category-list {
  .operation-bar {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    
    .el-button {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }

  .list-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .leaf-tag {
      margin-left: 8px;
    }
    
    :deep(.el-table) {
      border-radius: 8px;
      overflow: hidden;
    }
  }
  
  :deep(.el-form-item__content) {
    .el-tabs {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      border-radius: 8px;
      overflow: hidden;
      
      .el-tabs__content {
        padding: 20px;
      }
      
      .el-table {
        border-radius: 4px;
        overflow: hidden;
      }
    }
  }
  
  .attribute-template-item {
    :deep(.el-form-item__content) {
      width: 100%;
    }
  }
  
  .attribute-tabs {
    width: 100%;
    
    :deep(.el-tabs__nav) {
      background-color: #f5f7fa;
    }
    
    :deep(.el-tabs__item) {
      height: 50px;
      line-height: 50px;
      font-size: 15px;
      
      &.is-active {
        font-weight: bold;
        background-color: #fff;
      }
    }
  }
  
  .attributes-container {
    min-height: 180px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    
    :deep(.el-table) {
      margin-bottom: 10px;
      
      .el-input {
        width: 100%;
      }
    }
    
    :deep(.el-empty) {
      padding: 30px 0;
    }
  }
  
  .add-button-row {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    
    .el-button {
      width: 180px;
      border-radius: 20px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
    }
  }
  
  .category-form {
    padding: 0 15px;
    
    :deep(.el-form-item) {
      margin-bottom: 25px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
    
    :deep(.el-form-item__label) {
      font-weight: 500;
      padding-right: 20px;
    }
  }
  
  :deep(.el-dialog.category-dialog) {
    border-radius: 8px;
    overflow: hidden;
    
    .el-dialog__header {
      background-color: #f8f9fa;
      padding: 15px 20px;
      margin: 0;
      border-bottom: 1px solid #ebeef5;
      
      .el-dialog__title {
        font-size: 17px;
        font-weight: 600;
      }
    }
    
    .el-dialog__body {
      padding: 25px 30px;
    }
    
    .el-dialog__footer {
      border-top: 1px solid #ebeef5;
      padding: 15px 20px;
    }
    
    .el-button {
      border-radius: 20px;
      padding: 8px 20px;
    }
    
    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }
  }
  
  :deep(.el-cascader) {
    width: 100%;
  }
  
  :deep(.el-input) {
    border-radius: 4px;
  }
}
</style>
